import time
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.remote.webdriver import WebDriver


class BasePage(object):
    _black_list = [
        # 夜间提示切换护眼模式提示框，默认不切换元素
        (AppiumBy.XPATH, "/hierarchy/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.ScrollView/android.widget.LinearLayout/android.widget.Button[1]"),
        # 进入首页，是否同意获取存储权限提示框，默认同意元素
        (AppiumBy.XPATH,
         "/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.view.ViewGroup/android.widget.RelativeLayout/android.widget.FrameLayout[2]/android.webkit.WebView/android.webkit.WebView/android.view.View[6]/android.view.View[2]/android.view.View/android.view.View[4]")
    ]

    def __init__(self, driver: WebDriver):
        self.driver = driver

    def find_element(self, locator):
        return self.driver.find_element(*locator)
        # try:
        #     return self.driver.find_element(*locator)
        # except:
        #     time.sleep(2)
        #     self.handle_exception()
        #     self.driver.find_element(*locator)    # 重复多次查找
        #     return self.driver.find_element(*locator)

    def find_all_elements(self, locator):
        return self.driver.find_elements(*locator)

    def find_element_and_click(self, locator):
        self.driver.find_element(*locator).click()

    def handle_exception(self):
        for locator in self._black_list:
            elements = self.driver.find_element(*locator)
            if len(elements) >= 1:
                elements.click()
            else:
                print("%s not found" % locator)
